import { Injectable } from '@nestjs/common';
import { customAlphabet, nanoid } from 'nanoid'; // 用于生成短、唯一、随机字符串的工具库
import * as CryptoJS from 'crypto-js';
import { FastifyRequest } from 'fastify';

const RANDOM_VALUE = '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';

@Injectable()
export class UtilService {

  /**
   * 生成一个随机数
   * @param length
   * @param placeholder 指定生成随机字符串所使用的字符集
   * @returns
   */
  public generateRandomValue(length: number, placeholder = RANDOM_VALUE): string {
    const customNanoid = customAlphabet(placeholder, length);
    return customNanoid();
  }

  /**
   * 加密
   * @param value
   * @returns
   */
  public md5(value: string): string {
    return CryptoJS.MD5(value).toString();
  }

  /**
   * 生成一个UUID
   * @returns
   */
  public generateUUID(): string {
    return nanoid();
  }

  /**
   * 获取请求IP
   * @param req
   * @returns
   */
  getRequestIp(req: FastifyRequest): string {
    const ip = (req.headers['x-forwarded-for'] as string) || req.socket.remoteAddress;
    return ip.replace('::ffff:', '');
  }
}
